<template>
  <div class="app-container">
    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane label="按人员开课" name="user">
        <el-popover placement="top-start" width="400" trigger="hover">
          <p class="title">开课说明</p>
          <p>一：选择学习人员(可以选择多个)；</p>
          <p>二：选择需要开通的课程；</p>
          <p>三：点击确定查看开通课程与开课人员列表；</p>
          <p>四：点击顶部开通课程按钮开通课程；</p>
          <el-button slot="reference" size="mini" icon="el-icon-view">查看开课说明</el-button>
        </el-popover>
        <el-button type="primary" icon="el-icon-upload2" @click="importFile" size="small">批量开课</el-button>
        <el-row :gutter="20" style="margin-top: 30px;">
          <el-col :span="7">
            <div class="border">
              <div>
                <el-input
                  v-model="userData.mobile"
                  placeholder="请输入手机号"
                  size="mini"
                  style="width: 180px;"
                  @keyup.enter.native="searchUser"
                ></el-input>
                <el-button type="primary" @click="searchUser" size="mini">搜索</el-button>
              </div>
              <div class="scoll table-height">
                <el-table
                  ref="userTable"
                  :data="userList"
                  tooltip-effect="dark"
                  @selection-change="choseUser"
                >
                  <el-table-column type="selection" width="30"></el-table-column>

                  <el-table-column prop="userExpand.realname" label="姓名" align="left" width="100"></el-table-column>
                  <el-table-column prop="mobile" label="手机号" align="left"></el-table-column>
                </el-table>
              </div>

              <el-pagination
                layout="prev, pager, next"
                :pager-count="5"
                :total="userResultSize"
                :current-page="userData.currentPage"
                :page-count="userPageSize"
                @current-change="handleUserCurrentChange"
              ></el-pagination>
            </div>
          </el-col>
          <el-col :span="7">
            <div class="border">
              <div>
                <el-input
                  v-model="courseData.name"
                  placeholder="请输入课程名称"
                  size="mini"
                  style="width: 180px;"
                  @keyup.enter.native="searchCourse"
                ></el-input>
                <el-button type="primary" @click="searchCourse" size="mini">搜索</el-button>
              </div>
              <div class="scoll table-height">
                <el-table
                  ref="courseTable"
                  :data="courseList"
                  tooltip-effect="dark"
                  @selection-change="choseCourse"
                >
                  <el-table-column type="selection" width="30"></el-table-column>
                  <el-table-column prop="id" label="ID" align="center" width="60"></el-table-column>
                  <el-table-column prop="name" label="课程名称" align="left"></el-table-column>
                </el-table>
              </div>

              <el-pagination
                layout=" prev, pager, next"
                :total="courseResultSize"
                :current-page="courseData.currentPage"
                :page-count="coursePageSize"
                @current-change="handleCourseCurrentChange"
              ></el-pagination>
            </div>
          </el-col>
          <el-col :span="10" style="display: flex;justify-content: flex-start ;">
            <div style="margin: 300px 0 0 -20px;width: 20%;text-align: center;">
              <el-button @click="lookOpenCourse" size="mini" type="primary">
                确定
                <i class="el-icon-arrow-right el-icon--right"></i>
              </el-button>
            </div>
            <div class="border" style="position: relative;width: 80%;">
              <div>
                <el-button type="danger" size="mini" @click="openCourse">开通课程</el-button>
              </div>
              <div class="scoll table-height" style="height: 620px;">
                <el-table :data="lookChoseArray" :span-method="arraySpanMethod">
                  <el-table-column prop="user" label="用户"></el-table-column>
                  <el-table-column prop="courseName" label="开通课程"></el-table-column>
                  <el-table-column label="操作" width="100">
                    <template slot-scope="scope">
                      <el-button type="text" size="small" @click="deletChoseCourse(scope.row)">
                        移除
                        <i class="el-icon-delete"></i>
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-dialog title="批量开课" :visible.sync="dialogVisible" width="50%">
          <div>
            <div class="padt20">
              <span>*你可以下载设定好的批量导入的信息模板，输入内容后再上传</span>
              <span class="c-blue" @click="uploadXls">下载模板</span>
            </div>
            <div class="padt20">
              <el-upload
                ref="upload"
                class="upload-demo"
                :headers="{'Authorization':this.token}"
                :data="{cardRecordId:this.cardRecordId}"
                :on-success="uploadSuccess"
                :action="baseApi + uploadUrl"
                multiple
                :limit="3"
                :auto-upload="false"
              >
                <el-button
                  size="small"
                  icon="el-icon-upload"
                  type="primary"
                  @click="submitUpload"
                >点击上传</el-button>
                <span>*请上传后缀名为.xls,.xlsx的文件</span>
              </el-upload>
            </div>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitUpload">确 定</el-button>
          </span>
        </el-dialog>
      </el-tab-pane>
      <el-tab-pane label="按课程开课" name="course">
        <el-popover placement="top-start" width="400" trigger="hover">
          <p class="title">开课说明</p>
          <p>一：选择开通课程；</p>
          <p>二：上传开课人员；</p>
          <el-button slot="reference" size="mini" icon="el-icon-view">查看开课说明</el-button>
        </el-popover>

        <el-row :gutter="40" style="margin-top: 30px;">
          <el-col :span="12">
            <div class="border">
              <div>
                <el-input
                  v-model="courseData.name"
                  placeholder="请输入课程名称"
                  size="mini"
                  style="width: 180px;"
                  @keyup.enter.native="searchCourse"
                ></el-input>
                <el-button type="primary" @click="searchCourse" size="mini">搜索</el-button>
              </div>
              <div class="scoll table-height">
                <el-table
                  ref="courseTable"
                  :data="courseList"
                  tooltip-effect="dark"
                  @selection-change="choseOpenCourse"
                >
                  <el-table-column type="selection" width="30"></el-table-column>
                  <el-table-column prop="id" label="ID" align="center" width="60"></el-table-column>
                  <el-table-column prop="name" label="课程名称" align="left"></el-table-column>
                </el-table>
              </div>

              <el-pagination
                layout=" prev, pager, next"
                :total="courseResultSize"
                :current-page="courseData.currentPage"
                :page-count="coursePageSize"
                @current-change="handleCourseCurrentChange"
              ></el-pagination>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="border" style="position: relative;width: 80%;">
              <div>
                <el-button
                  type="primary"
                  icon="el-icon-upload2"
                  size="small"
                  @click="courseDialogVisible = true"
                >上传开课人员</el-button>
              </div>
              <div class="scoll table-height" style="height: 620px;">
                <el-table :data="choseOpenCourseArray">
                  <el-table-column prop="name" label="开通课程"></el-table-column>
                  <el-table-column label="操作" width="100">
                    <template slot-scope="scope">
                      <el-button type="text" size="small" @click="deletChoseOpenCourse(scope.row)">
                        移除
                        <i class="el-icon-delete"></i>
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-dialog title="批量开课" :visible.sync="courseDialogVisible" width="50%">
          <div>
            <div class="padt20">
              <span>*你可以下载设定好的批量导入的信息模板，输入内容后再上传</span>
              <span class="c-blue" @click="uploadCourseXls">下载模板</span>
            </div>
            <div class="padt20">
              <el-upload
                ref="courseUpload"
                class="upload-demo"
                :data="{cardRecordId:this.cardRecordId,courseIds:this.courseIds}"
                :on-success="uploadSuccess"
                :action="baseApi + courseUploadUrl"
                multiple
                :limit="3"
                :auto-upload="false"
              >
                <el-button
                  size="small"
                  icon="el-icon-upload"
                  type="primary"
                  @click="submitCourseUpload"
                >点击上传</el-button>
                <span>*请上传后缀名为.xls,.xlsx的文件</span>
              </el-upload>
            </div>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="courseDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitCourseUpload">确 定</el-button>
          </span>
        </el-dialog>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { Message } from "element-ui";
import { getCourseListForOpen, openCourse } from "@/api/course";
import { getStudentList } from "@/api/student";
import { baseApi } from "@/utils/index";
import { import_department } from "@/api/student";
export default {
  name: "news",
  data() {
    return {
      baseApi: "",
      activeName: "user",
      userPageSize: 0,
      userResultSize: 0,
      courseResultSize: 0,
      coursePageSize: 0,
      cardRecordId: "", //学习卡记录id
      userData: {
        currentPage: 1,
        mobile: "",
        companyId: ""
      },
      courseData: {
        currentPage: 1,
        name: ""
      },
      courseList: [],
      userList: [],
      lookChoseArray: [], //查看选中用户与课程后的数组
      openCourseArray: [], //用于发送请求数据
      choseUserArray: [],
      choseCourseArray: [],
      dialogVisible: false, //以人为单位开课
      uploadUrl: "/card/user/importOpenCourse",
      importUrl: "/asset/file/import_open_course.xls",
      choseOpenCourseArray: [], //以课为单位
      courseIds: [],
      courseDialogVisible: false,
      courseUploadUrl: "/card/user/importOpenUser",
      courseImportUrl: "/asset/file/import_open_user.xls"
    };
  },
  watch: {
    choseOpenCourseArray() {
      this.courseIds = [];
      this.choseOpenCourseArray.forEach(item => {
        this.courseIds.push(item.id);
      });
    }
  },
  created() {
    let query = this.$route.query;
    this.userData.companyId = query.companyId;
    this.cardRecordId = query.cardRecordId;
    this.baseApi = baseApi();
    this.getUserList(this.userData);
    this.getCourseList(this.courseData);
  },
  methods: {
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      let that = this;

      if (columnIndex === 0) {
        if (row.rowspan) {
          return {
            rowspan: row.rowspanNum,
            colspan: 1
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }
    },
    getUserList(data) {
      getStudentList(data).then(res => {
        let entitys = res.entity;
        this.userList = [...entitys.data];
        this.userPageSize = entitys.page.totalPageSize;
        this.userResultSize = entitys.page.totalResultSize;
      });
    },
    getCourseList(data) {
      getCourseListForOpen(data).then(res => {
        let entitys = res.entity;
        this.courseList = [...entitys.data];
        this.coursePageSize = entitys.page.totalPageSize;
        this.courseResultSize = entitys.page.totalResultSize;
      });
    },
    choseCourse(data) {
      this.choseCourseArray = data;
    },
    choseUser(data) {
      this.choseUserArray = data;
    },
    choseOpenCourse(data) {
      this.choseOpenCourseArray = data;
    },
    lookOpenCourse() {
      let that = this;
      var tableArr = [];
      this.choseUserArray.forEach(userItem => {
        this.choseCourseArray.forEach((courserItem, index) => {
          var rowspan = index == 0;
          tableArr.push({
            courseId: courserItem.id,
            courseName: courserItem.name,
            sourceprice: courserItem.sourceprice,
            currentprice: courserItem.currentprice,
            user: userItem.userExpand.realname,
            userId: userItem.id,
            rowspan: rowspan,
            rowspanNum: this.choseCourseArray.length - index
          });
        });
      });
      if (that.lookChoseArray != null && that.lookChoseArray.length > 0) {
        let length = that.lookChoseArray.length;
        let tableData = that.lookChoseArray;
        let overBreak = false;
        for (let j = 0; j < length; j++) {
          for (var i = 0; i < tableArr.length; i++) {
            if (tableData[j].userId == tableArr[i].userId) {
              tableArr[i].rowspanNum += tableData[j].rowspanNum;
              tableData[j].rowspan = false;
              overBreak = true;
              break;
            }
          }
          if (overBreak) {
            break;
          }
        }

        that.lookChoseArray = that.lookChoseArray.concat(tableArr);
      } else {
        that.lookChoseArray = tableArr;
      }
      that.lookChoseArray.sort(function(a, b) {
        var idc = a.userId - b.userId;
        if (idc == 0) {
          idc = a.rowspanNum - b.rowspanNum;
        }
        return -idc;
      });
      this.choseCourseArray = [];
      this.choseUserArray = [];
      this.$refs.userTable.clearSelection();
      this.$refs.courseTable.clearSelection();
    },
    searchUser() {
      this.userData.currentPage = 1;
      this.getUserList(this.userData);
    },
    searchCourse() {
      this.courseData.currentPage = 1;
      this.getCourseList(this.courseData);
    },
    handleUserCurrentChange(val) {
      this.userData.mobile = "";
      this.userData.currentPage = val;
      this.getUserList(this.userData);
    },
    handleCourseCurrentChange(val) {
      this.courseData.name = "";
      this.courseData.currentPage = val;
      this.getCourseList(this.courseData);
    },
    deletChoseCourse(row) {
      let currentIndex = this.lookChoseArray.indexOf(row);
      this.lookChoseArray.splice(currentIndex, 1);
      let length = this.lookChoseArray.length;
      let currentArray = this.lookChoseArray;
      //遍历重新绘制合并表格
      for (let i = 0; i < length; i++) {
        if (row.userId == currentArray[i].userId) {
          if (currentArray[i].rowspan) {
            currentArray[i].rowspanNum -= 1;
          } else {
            currentArray[i].rowspan = true;
            currentArray[i].rowspanNum = row.rowspanNum - 1;
          }
          break;
        }
      }
    },
    deletChoseOpenCourse(row) {
      let currentIndex = this.choseOpenCourseArray.indexOf(row);
      this.choseOpenCourseArray.splice(currentIndex, 1);
    },
    openCourse() {
      this.openCourseArray = [];
      this.lookChoseArray.forEach(item => {
        let { userId, courseId, courseName, sourceprice, currentprice } = item;
        this.openCourseArray.push({
          userId,
          courseId,
          courseName,
          sourceprice,
          currentprice
        });
      });
      if (this.openCourseArray.length == 0) {
        this.$message({
          type: "info",
          message: "请选择开通课程"
        });
      } else {
        this.$confirm("确定开通课程, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            openCourse(this.cardRecordId, this.openCourseArray).then(res => {
              if (res.status == "1" || res.success) {
                this.$message({
                  type: "success",
                  message: res.message
                });
                this.lookChoseArray = [];
                this.openCourseArray = [];
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消"
            });
          });
      }
    },
    importFile() {
      this.dialogVisible = true;
    },
    uploadXls() {
      let urls = baseApi() + this.importUrl;
      window.open(urls);
    },
    uploadCourseXls() {
      let urls = baseApi() + this.courseImportUrl;
      window.open(urls);
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
    submitCourseUpload() {
      this.$refs.courseUpload.submit();
    },
    uploadSuccess(response, file, fileList) {
      let data = response;
      if (data.status == 1) {
        Message({
          message: data.message,
          type: "success",
          duration: 2000
        });
        this.closeDialog();
      } else {
        let htmlMsg =
          '<h3 style="text-align:center;margin-top:0;">' +
          data.message +
          "</h3>";
        data.entity.forEach(item => {
          htmlMsg += '<p style="padding-bottom:10px;">' + item + "</p>";
        });

        Message({
          message: htmlMsg,
          type: "error",
          duration: 0,
          showClose: true,
          dangerouslyUseHTMLString: true
        });
        if (this.dialogVisible) {
          this.$refs.upload.clearFiles();
        } else {
          this.$refs.courseUpload.clearFiles();
        }
      }
    },
    closeDialog() {
      this.dialogVisible = false;
    },
    handleClick() {
      this.courseData = {
        currentPage: 1,
        name: ""
      };
      this.getCourseList(this.courseData);
    }
  },
  computed: {
    ...mapGetters(["token"])
  }
};
</script>

<style  rel="stylesheet/scss" lang="scss" scoped>
.info {
  padding: 15px;
  border: 1px solid #d1dbe5;
  color: #555;
  font-size: 14px;
}

.title {
  color: #555;
  font-size: 16px;
  font-weight: bold;
}

.border {
  height: 80%;
  padding: 15px;
  border: 1px solid #d1dbe5;
}

.table-height {
  height: 580px;
  overflow-y: scroll;
}

.padt20 {
  padding-bottom: 20px;
}
.c-blue {
  color: #409eff;
  cursor: pointer;
}

.row-container {
  .el-col {
    margin-left: 20px;
    margin-top: 30px;
    height: 500px;
    border: 1px solid #ddd;
    padding: 30px;
    span {
      padding: 15px;
      font-size: 12px;
      color: #606266;
    }
    .c-black {
      color: #1d2026;
      padding-bottom: 10px;
    }
    p {
      font-size: 14px;
      color: #606266;
      padding-left: 15px;
      line-height: 23px;
    }

    .span-title {
      padding-right: 20px;
    }
    .buton-contain {
      margin: 50px 0 0 50px;
    }
    .title {
      font-size: 14px;
      font-weight: bold;
    }
    .img-contain {
      padding: 15px;
      padding-bottom: 0;
      img {
        max-width: 100%;
      }
    }
  }
}
</style>